from django.shortcuts import render_to_response
from django.db.models import Count
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from django.http import Http404, HttpResponse
from note.models import Note,Tag
def index(request):
    n_list = Note.objects.all()
    t_list = Tag.objects.annotate(Count('note')).order_by('-note__count')
    t_color_list= []
    temp = 1
    for i in t_list:
        t_color_list.append({'tag':i,'class':'color' + str(temp)})
        temp += 1
        
    n_count = len(n_list)    
    return render_to_response('note/index.html',{'notes':n_list,'tags':t_list,'notescount':n_count,'tagclass':t_color_list})

def addnote(request):
    errors = []
    if not request.POST.get('notetitle', ''):
        errors.append('Enter a Title')
    if not request.POST.get('notecontent',''):
        errors.append('Enter a message')
    if not errors:
        nt = request.POST['notetitle']
        nc = request.POST['notecontent']
        temp = nc.split(' ')
        tags = []
        content = []
        for i in temp:            
            if '#' in i:
                tags.append(i.replace('#',''))
            else:
                content.append(i)

        nc = ' '.join(content)
        note = Note(title=nt,content=nc)
        note.save()
        #add Tags
        for i in tags:
            tag = Tag.objects.filter(name=i)
            if tag:
                note.tags.add(tag[0])
            else:
                tempTag = Tag(name=i)
                tempTag.save()
                note.tags.add(tempTag)
        return HttpResponseRedirect('/note/')
    #error
    return render_to_response('note/add.html',{'errors':errors})
    
def viewbytag(request, offset):
    if offset:
        current_tag_name = offset
        current_tags = Tag.objects.filter(name=current_tag_name)
        
            
        if current_tags:
            current_tag = current_tags[0]
            n_list = current_tag.note_set.all()
            t_list = Tag.objects.annotate(Count('note')).order_by('-note__count')
            n_count = len(Note.objects.all())
            t_color_list= []
            temp = 1
            for i in t_list:
                t_color_list.append({'tag':i,'class':'color' + str(temp)})
                temp += 1
            return render_to_response('note/tag.html',{'notes':n_list,'tags':t_list,'ctag':current_tag,'notescount':n_count,'tagclass':t_color_list})
    #error
    return HttpResponseRedirect('/note/')
    
